using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Metadata;
using Zack.DomainCommons.Models;

namespace Microsoft.EntityFrameworkCore;
public static class EFCoreExtensions
{
    public static void MyEnableSoftDeletionGlobalFilter(this ModelBuilder modelBuilder)
    {
        foreach (IMutableEntityType item in from e in modelBuilder.Model.GetEntityTypes()
                                            where e.ClrType.IsAssignableTo(typeof(ISoftDelete))
                                            select e)
        {
            IMutableProperty mutableProperty = item.FindProperty("IsDeleted")!;
            ParameterExpression parameterExpression = Expression.Parameter(item.ClrType, "p");
            LambdaExpression queryFilter = Expression.Lambda(Expression.Not(Expression.Property(parameterExpression, mutableProperty.PropertyInfo!)), parameterExpression);
            item.SetQueryFilter(queryFilter);
        }
    }

    public static IQueryable<T> Query<T>(this DbContext ctx) where T : class, IEntity
    {
        return EntityFrameworkQueryableExtensions.AsNoTracking(ctx.Set<T>());
    }
}